;; set represent as ordered list

(define (element-of-set? x set) ;; set is an ordered list
  (cond ((null? set) #f)
        ((= x (car set)) #t)
        ((> x (car set)) (element-of-set? x (cdr set)))
        (else #f)))

(define (adjion-set x set) ;; set is an ordered list
  (cond ((null? set) x)
        ((= x (car set)) set)
        ((< x (car set)) (cons x set))
        ((> x (car set)) 
         (cons (car set) (adjion-set x (cdr set))))))

(define (intersection-set set1 set2)
  (cond ((or (null? set1) (null? set2)) '())
        (else (let ((e1 (car set1))
                    (e2 (car set2)))
                (cond ((< e1 e2) 
                       (intersection-set (cdr set1) set2))
                      ((= e1 e2) 
                       (cons e1 (intersection-set (cdr set1) (cdr set2))))
                      ((> e1 e2) 
                       (intersection-set set1 (cdr set2))))))))
                     
(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((null? set2) set1)
        (else (let ((e1 (car set1))
                    (e2 (car set2)))
                (cond ((< e1 e2) 
                       (cons e1 (union-set (cdr set1) set2)))
                      ((= e1 e2) 
                       (cons e1 (union-set (cdr set1) (cdr set2))))
                      ((> e1 e2) 
                       (cons e2 (union-set set1 (cdr set2)))))))))
  
;; Test element-of-set?
(element-of-set? 1 '())
(element-of-set? 1 '(1))
(element-of-set? 1 '(1 2))
(element-of-set? 1 '(2 3))

;; Test adjoin-set
(adjion-set 1 '())
(adjion-set 1 '(1))
(adjion-set 1 '(1 2))

;; Test intersection-set and union-set
(define odd '(1 3 5 7))
(define even '(0 2 4 6))
(intersection-set odd even)
(union-set odd even)
(union-set '() '())
